﻿/**
* HtmlExt.js
* 
* @author Demis Bellot
* @version 1.0
* @requires Class.js, StringExt.js
*
* Copyright 2009, Demis Bellot
* http://code.google.com/p/ajaxstack/
*/

var H = H || {};
H.createTable = function(oRows, tableOptions)
{
	tableOptions = tableOptions || {};
	var theadHtml = "";
	var trHtml = "";

	for (var i in oRows)
	{
		var oData = oRows[i];
		if (!theadHtml)
		{
			for (var key in tableOptions.showFields)
			{
				theadHtml += "<th>" + tableOptions.showFields[key] + "</th>";
			}
		}
		var rowClassName = i % 2 == 0 ? "odd" : "even";
		if (tableOptions.rowClass)
		{
			rowClassName += is.Function(tableOptions.rowClass)
				? " " + tableOptions.rowClass(oData)
				: " " + tableOptions.rowClass;
		}
		trHtml += "<tr class='" + rowClassName + "'>";

		for (var key in tableOptions.showFields)
		{
			var label = tableOptions.showFields[key];
			var val = is.Function(oData[key]) ? oData[key]() : oData[key];
			if (!val)
			{
				val = "";
			}
			if (tableOptions.maxFieldLength && val.indexOf("<") == -1)
			{
				val = S.cropText(val, tableOptions.maxFieldLength);
			}
			trHtml += "<td>" + val + "</td>";
		}

		trHtml += "</tr>";
	}
	var tableHtml = "<table class='" + tableOptions.tableClassName + "'><thead><tr>" + theadHtml + "</tr></thead><tbody>" + trHtml + "</tbody></table>";
	return tableHtml;
}

H.navLink = function(attrs, innerHtml)
{
	return H.actionLink(attrs, innerHtml, 'nav-link');
}

H.actionLink = function(attrs, innerHtml, linkClass)
{
	linkClass = linkClass || 'action-link';
	var tag = "span";
	if (attrs['tag'])
	{
		tag = attrs['tag'];
		delete attrs['tag'];
	}
	if (attrs['action'])
	{
		var action = attrs['action'];
		if (is.TypeOf(action, Path.getType())) action = action.toUrl();
		attrs['href'] = is.Array(action) ? H.pathInfoHash(action) : '#' + action;
		delete attrs['action'];
	}
	attrs['class'] = attrs['class'] ? attrs['class'] + ' ' + linkClass : linkClass;
	return H.tag(tag, attrs, innerHtml);
}

H.safeAttr = function(attrValue)
{
	return attrValue.toString().replace('"', '\\"');
}

H.pathInfo = function(parts)
{
	var attr = "";
	for (i in parts)
	{
		if (attr) attr += "/";
		attr += H.safeAttr(parts[i]);
	}
	return attr;
}

H.pathInfoHash = function(parts)
{
	return '#' + H.pathInfo(parts);
}

